﻿using I_Authorization.Domains.Organization;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Read.API.Application.Commons.DepartmentCommons;
using LinqKit;
using MediatR;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System.Linq;
using System.Linq.Expressions;
using System.Xml.Linq;

namespace I_Authorization.Read.API.Application.CommandHandlers.DepartmentHandlers
{
    /// <summary>
    /// 部门显示
    /// </summary>
    public class DepartmentShowCommonsHandlers : IRequestHandler<DepartmentShowCommons, Page<Department>>
    {
        private readonly IDepartmentRepository _department;
        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="department"></param>
        public DepartmentShowCommonsHandlers(IDepartmentRepository department)
        {
            _department = department;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Page<Department>> Handle(DepartmentShowCommons request, CancellationToken cancellationToken)
        {
            #region 委托转换查询
            //定义委托数
            Expression<Func<Department, bool>> i = c => true && c.IsDel != true;
            //部门名称
            if (!string.IsNullOrEmpty(request.DepartName))
            {
                Expression<Func<Department, bool>> a = c => c.DepartName.Contains(request.DepartName);
                i = i.And(a);
            }
            var List = await _department.GetAsync(i);
            int totalCount = List.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.size);
            List = List.OrderByDescending(c=>c.DepartId).Skip(request.size * (request.page - 1)).Take(request.size).ToList();

            return new Page<Department>
            {
                tatalCount = totalCount,
                pageCount = pageCount,
                Data = List
            };

            #endregion

            //查询


            //if (!string.IsNullOrEmpty(request.DepartName))
            //{
            //    List = await _department.GetAsync(c => c.DepartName.Contains(request.DepartName) && !c.IsDel == true);
            //}
            //if (!string.IsNullOrEmpty(request.Departtype))
            //{
            //    List = await _department.GetAsync(c => c.Departtype.Contains(request.Departtype) && !c.IsDel == true);
            //}
            //if (request.DepartState > 0)
            //{
            //    List = await _department.GetAsync(c => c.DepartState == request.DepartState && !c.IsDel == true);
            //}

        }
    }
}
